// Copyright 2021 by 马万里. All rights reserved.
// 开发团队 ：   鸡中之霸
// 开发人员 ：   马万里
// 开发时间 ：   2021/2/21 16:01
// 文件名称 ：   main.go
// 工程名称 ：   videostream
// 开发工具 ：   GoLand
//

package main

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"johnsonsmile.com/videostream/api/session"
	"net/http"
)

type middleWareHandler struct {
	r *httprouter.Router
}

func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 检查session
	validateUserSession(r)
	m.r.ServeHTTP(w, r)
}

func NewMiddlerWareHandler(r *httprouter.Router) http.Handler {
	m := middleWareHandler{}
	m.r = r
	return m
}

func RegisterHandlers() *httprouter.Router {
	router := httprouter.New()
	router.POST("/user", Register)
	router.POST("/user/:username", Login)
	router.GET("/user/:username", GetUserInfo)
	router.POST("/user/:username/videos", AddNewVideo)
	router.GET("/user/:username/videos", ListAllVideos)
	router.DELETE("/user/:username/videos/:vid", DeleteVideo)
	router.POST("/videos/:vid/comments", PostComment)
	router.GET("/videos/:vid-id/comments", ShowComments)
	return router
}

func Prepare() {
	session.LoadSessionFromDB()
}

func main() {
	Prepare()
	r := RegisterHandlers()
	mh := NewMiddlerWareHandler(r)
	err := http.ListenAndServe(":8080", mh)
	if err != nil {
		fmt.Println(err)
	}
}
